package com.shensi.adminCollect.service.station.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.shensi.adminCollect.common.constant.UserConstants;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.entity.SysUser;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.exception.BaseException;
import com.shensi.common.core.exception.CustomException;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.domain.station.StationOillGun;
import com.shensi.adminCollect.domain.station.dto.AddStationSettleInfoDto;
import com.shensi.adminCollect.domain.station.img;
import com.shensi.adminCollect.domain.station.vo.StationByEnterpriseVo;
import com.shensi.adminCollect.domain.station.vo.StationEnterpriseCopInfo;
import com.shensi.adminCollect.domain.station.vo.StationResVo;
import com.shensi.adminCollect.domain.station.vo.StationVo;
import com.shensi.adminCollect.mapper.station.StationEnterpriseCopMapper;
import com.shensi.adminCollect.mapper.station.StationMapper;
import com.shensi.adminCollect.mapper.station.StationOillGunMapper;
import com.shensi.adminCollect.service.station.IStationService;
import com.shensi.adminCollect.service.station.MemberManagementService;
import com.shensi.adminCollect.service.station.TeamManagementService;
import com.shensi.adminCollect.mapper.system.SysUserMapper;
import com.shensi.adminCollect.service.system.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 油站信息Service业务层处理
 * 
 * @author qujia
 * @date 2020-12-08
 */
@Service
@Slf4j
public class StationServiceImpl implements IStationService
{
    @Autowired
    private StationMapper stationMapper;

    @Autowired
    private IStationService stationService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private StationEnterpriseCopMapper stationEnterpriseCopMapper;

    @Autowired
    private TeamManagementService teamManagementService;

    @Autowired
    private MemberManagementService memberManagementService;

    @Autowired
    private StationOillGunMapper stationOillGunMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询油站信息
     *
     * @param stationId 油站信息ID
     * @return 油企信息
     */
    public Station selectStationById(Long stationId){
        return  stationMapper.selectStationById(stationId);
    }

    @Override
    public List<Station> getStationByEnterpriseId(Long enterpriseId) {
        return stationMapper.getStationByEnterpriseId(enterpriseId);
    }

    public Station selectStationByName(String stationName){
        return stationMapper.selectStationByName(stationName);
    }

    @Override
    public void addStationSettleInfo(AddStationSettleInfoDto addStationSettleInfoDto) {
        stationMapper.updateStationSettleInfo(addStationSettleInfoDto);
    }

    @Override
    public AddStationSettleInfoDto getStationSettleInfo(String stationId) {
        Long stationIdLong;
        try {
             stationIdLong = Long.valueOf(stationId);
        }catch (Exception e){
            throw new CustomException("油站id格式错误");
        }
        return stationMapper.getStationSettleInfo(stationIdLong);
    }

    @Override
    public int setShowCommisson(Station station) {

        return  stationMapper.setShowCommisson(station);
    }

    @Override
    public int setOpenStaffClass(Station station) {

        return  stationMapper.setOpenStaffClass(station);
    }

    @Override
    public int setShowPaymentCommission(Station station) {
        if(Objects.nonNull(station) && Objects.nonNull(station.getPhysicalCardAmount())){
            if(station.getPhysicalCardAmount().compareTo(BigDecimal.ZERO) < 0){
                throw new BaseException("实体卡消费额度下限不能小于0");
            }
            if(station.getPhysicalCardAmount().toString().length() > 13){
                throw new BaseException("实体卡消费额度下限太大");
            }
        }
        return  stationMapper.setShowPaymentCommission(station);
    }


    @Override
    public List<StationByEnterpriseVo> getStationByEnterprise(Long enterpriseId) {

        ArrayList<StationByEnterpriseVo> stationByEnterpriseVos = new ArrayList<>();

        LoginUser current = SecurityUtils.getLoginUser();
        SysUser user = current.getUser();

        if (enterpriseId != null){
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);
            station.setDeleteStatus("0");
            List<Station> stations = stationMapper.selectStationList(station);
            for (Station stationInfo : stations) {
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                BeanUtil.copyProperties(stationInfo,stationByEnterpriseVo);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
            }
            return stationByEnterpriseVos;
        }


        if (UserConstants.LEVEL_TWO.equals(user.getUserLevel())){
            Station station = new Station();
            station.setEnterpriseId(user.getEnterpriseId());
            station.setDeleteStatus("0");

            List<Station> stations = stationMapper.selectStationList(station);
            for (Station stationInfo : stations) {
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                BeanUtil.copyProperties(stationInfo,stationByEnterpriseVo);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
            }
                return stationByEnterpriseVos;
            }
        if (UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
            Station station = new Station();
            station.setStationId(user.getStationId());
            station.setDeleteStatus("0");
            List<Station> stations = stationMapper.selectStationList(station);
            if (CollectionUtil.isNotEmpty(stations)){
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                BeanUtil.copyProperties(stations.get(0),stationByEnterpriseVo);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
            }
            return stationByEnterpriseVos;
        }
            if (UserConstants.LEVEL_FIVE.equals(user.getUserLevel())){
                List<Long> managerEnterpriseId = teamManagementService.getManagerEnterpriseId(user.getUserId());
                if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                    for (Long enId : managerEnterpriseId) {
                        Station station = new Station();
                        station.setEnterpriseId(enId);
                        station.setDeleteStatus("0");

                        List<Station> stations = stationMapper.selectStationList(station);
                        for (Station stationInfo : stations) {
                            StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                            BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                            stationByEnterpriseVos.add(stationByEnterpriseVo);
                        }
                    }
                }
                return stationByEnterpriseVos;
            }

            if (UserConstants.LEVEL_SIX.equals(user.getUserLevel())) {
                List<Long> managerEnterpriseId = memberManagementService.getMemberEnterpriseId(user.getUserId());
                if (CollectionUtil.isNotEmpty(managerEnterpriseId)) {
                    for (Long enId : managerEnterpriseId) {
                        Station station = new Station();
                        station.setEnterpriseId(enId);
                        station.setDeleteStatus("0");

                        List<Station> stations = stationMapper.selectStationList(station);
                        for (Station stationInfo : stations) {
                            StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                            BeanUtil.copyProperties(stationInfo, stationByEnterpriseVo);
                            stationByEnterpriseVos.add(stationByEnterpriseVo);
                        }
                    }
                    return stationByEnterpriseVos;
                }
            }

        if (UserConstants.LEVEL_ONE.equals(user.getUserLevel()) || StringUtils.isBlank(user.getUserLevel())){
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);
            station.setDeleteStatus("0");

            List<Station> stations = stationMapper.selectStationList(station);
            if(CollectionUtil.isNotEmpty(stations)){
                for (Station stationInfo : stations) {
                    StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                    BeanUtil.copyProperties(stationInfo,stationByEnterpriseVo);
                    stationByEnterpriseVos.add(stationByEnterpriseVo);
                }
                return stationByEnterpriseVos;
            }

        }

        return stationByEnterpriseVos;
    }

    @Override
    public List<StationByEnterpriseVo> getStationInfo() {
        ArrayList<StationByEnterpriseVo> stationByEnterpriseVos = new ArrayList<>();
        //获取用户信息
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (sysUser.getUserLevel().equals("1")){
            Long enterpriseId = sysUser.getEnterpriseId();
            Station station = new Station();
            station.setEnterpriseId(enterpriseId);
            station.setStatus("1");
            station.setDeleteStatus("0");
            List<Station> stations = stationMapper.selectStationList(station);
            if (CollectionUtil.isNotEmpty(stations)){
                for (Station station1 : stations) {
                    Long stationId = station1.getStationId();
                    String stationName = station1.getStationName();
                    StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                    stationByEnterpriseVo.setStationId(stationId);
                    stationByEnterpriseVo.setStationName(stationName);
                    stationByEnterpriseVos.add(stationByEnterpriseVo);
                }
                return stationByEnterpriseVos;
            }
        }else if (sysUser.getUserLevel().equals("2")){
            Station station = stationMapper.selectStationById(sysUser.getStationId());
            if (Objects.nonNull(station)){
                if (!station.getStatus().equals("1") || !station.getDeleteStatus().equals("0")){
                    return stationByEnterpriseVos;
                }
                String stationName = station.getStationName();
                Long stationId = station.getStationId();
                StationByEnterpriseVo stationByEnterpriseVo = new StationByEnterpriseVo();
                stationByEnterpriseVo.setStationId(stationId);
                stationByEnterpriseVo.setStationName(stationName);
                stationByEnterpriseVos.add(stationByEnterpriseVo);
                return stationByEnterpriseVos;
            }
        }
        return null;
    }

    @Override
    public List<Long> getStationByEnterpriseList(List<Long> enterpriseId) {

        return stationMapper.selectStationListByEnterpriseIds(enterpriseId);
    }

    @Override
    public List<Long> getStationIdList(Station station) {
        return  stationMapper.getStationIdList(station);
    }

    @Override
    public List<Station> selectStationListByEnterpriseId(Long enterpriseId) {
        return stationMapper.selectStationListByEnterpriseId(enterpriseId);
    }

    @Override
    @Transactional
    public int logicallyDelete(Long stationId) {
        int i=0;
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //防止修改其他参数
        Station station1=new Station();
        station1.setStationId(stationId);
        station1.setDeleteDate(new Date());
        station1.setDeleteStatus("1");
        station1.setDeleteUser(currentUser.getUser().getUserId());
        i=i+updateStation(station1);
        //逻辑删除油站的油品油枪
        StationOillGun stationOillGun=new StationOillGun();
        stationOillGun.setStationId(stationId);
        stationOillGun.setDeleteUser(currentUser.getUser().getUserId());
        stationOillGun.setDeleteStatus("1");
        stationOillGun.setDeleteDate(new Date());
        i=i+stationOillGunMapper.updateStationOillGunByStationId(stationOillGun);
        //删除油站员工
        SysUser sysUser=new SysUser();
        sysUser.setStationId(stationId);
        sysUser.setDelFlag("2");//数据库字段描述2代表删除
        i=i+sysUserMapper.updateByStationId(sysUser);
        return i;
    }
    /**
     * 查询油站信息列表
     *
     * @param station 油站信息
     * @return 油站信息集合
     */
    public List<Station> transactionStationList( Station station){
        return  stationMapper.transactionStationList(station);

    }

    /**
     * 查询油站信息列表
     *
     * @param station 油站信息
     * @return 油站信息集合
     */
    public List<Station> selectStationList( Station station){
        return  stationMapper.selectStationList(station);

    }

    /**
     * 新增油站信息
     *
     * @param station 油站信息
     * @return 结果
     */
    public int insertStation(Station station){
        return  stationMapper.insertStation(station);
    }

    @Transactional
    public AjaxResult addStation(StationVo stationVo){
        StationEnterpriseCopInfo stationEnterpriseCopInfo = new StationEnterpriseCopInfo();
        stationEnterpriseCopInfo.setCopId(stationVo.getCopId());
        stationEnterpriseCopInfo.setType(2);
        StationEnterpriseCopInfo copIdRes = stationEnterpriseCopMapper.selectByCopId(stationEnterpriseCopInfo);
        if(Objects.nonNull(copIdRes)){
            Station station = new Station();
            station.setStationId(copIdRes.getStationId());
            station.setStationName(stationVo.getStationName());
            Station stationRes = stationMapper.selectStationById(copIdRes.getStationId());
            stationMapper.updateStation(station);
            return AjaxResult.success("更新油站成功", stationRes.getStationCode());
        }


        Calendar cal = Calendar.getInstance();
        int m = 0;
        Random random=new Random();
        String result1 = "";
        for (int i = 0; i < 4; i++) {
            result1 += random.nextInt(10);
        }
        int year = cal .get(Calendar.YEAR);
        int month = cal .get(Calendar.MONTH) + 1;
        int yearcount=year-2000;
        String code="S"+yearcount+month+"0001"+result1;
        Station station = new Station();
        station.setEnterpriseId(stationVo.getEnterpriseId());
        station.setStationCode(code);
        station.setStatus(stationVo.getStatus());
        station.setStationName(stationVo.getStationName());
        m = stationMapper.insertStation(station);
        if(m<=0){
            return  AjaxResult.error("新增失败");
        }


        stationEnterpriseCopInfo.setType(2);
        stationEnterpriseCopInfo.setStationId(station.getStationId());
        stationEnterpriseCopInfo.setEnterpriseId(stationVo.getEnterpriseId());
        Integer res = stationEnterpriseCopMapper.insertInfo(stationEnterpriseCopInfo);
        if(res<=0){
            return AjaxResult.error("新增失败");
        }

        Long[] roles={Long.parseLong(19+"")};
        //Station station1=stationService.selectStationList(station).get(0);
        SysUser sysUser=new SysUser();
        sysUser.setDeptId((long) 100);
        sysUser.setUserName(code);
        sysUser.setNickName(station.getStationName());
        sysUser.setUserLevel("2");
        sysUser.setPhonenumber(station.getPhone());
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setStationId(station.getStationId());
        sysUser.setRoleIds(roles);
        sysUser.setEnterpriseId(station.getEnterpriseId());
        int i = sysUserService.insertUser(sysUser);
        if(i <= 0){
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success("新增油站成功", code);
    }

    /**
     * 修改油站信息
     *
     * @param station 油企信息
     * @return 结果
     */
    @CacheEvict(value = { "EnterpriseServiceImpl_selectStaInfoList"},
            key="'e_' + #root.args[0].getEnterpriseId()",
            condition = "#root.args[0] != null"
    )
    public int updateStation(Station station){
        station.setUpdatedTime(new Date());
        return  stationMapper.updateStation(station);
    }

    /**
     * 删除油站信息
     *
     * @param stationId 油企信息ID
     * @return 结果
     */
    public int deleteStationById(Long stationId){
        return  stationMapper.deleteStationById(stationId);
    }

    /**
     * 批量删除油站信息
     *
     * @param stationIds 需要删除的数据ID
     * @return 结果
     */
    public int deleteStationByIds(Long[] stationIds){
        return  stationMapper.deleteStationByIds(stationIds);
    }

    @Override
    @Transactional
    public List<StationResVo> batchInsertStation(List<Station> stationList) throws Exception {
        ArrayList<StationResVo> stationResVoList = new ArrayList<>();
        for (Station station : stationList) {
            StationResVo stationResVo = new StationResVo();
            String stationName = station.getStationName();
            Station stationByName = stationService.selectStationByName(stationName);
            if(Objects.nonNull(stationByName)){
                throw new CustomException("存在重复的油站名");
            }
            log.info("新增油站{}", station);
            int m=0;
            Calendar cal = Calendar.getInstance();
            String regionData1="";
            String licenseImg="";
            String ImgName="";
            if (station.getRegionDataList() !=null&&station.getRegionDataList().length>0) {
                for (String regionData : station.getRegionDataList()) {
                    if ("".equals(regionData1)) {
                        regionData1 += regionData;
                    } else {
                        regionData1 += "," + regionData;
                    }
                }

                if (!"".equals(regionData1)) {
                    station.setRegionData(regionData1);
                }
            }
            if (station.getImgFileList()!=null&&station.getImgFileList().size()>0) {
                for (img img1 : station.getImgFileList()) {
                    if ("".equals(licenseImg)) {
                        licenseImg += img1.getUrl();
                        ImgName +=img1.getName();
                    } else {
                        licenseImg +="," +img1.getUrl();
                        ImgName +=","+img1.getName();
                    }
                }

                if (!"".equals(licenseImg)) {
                    station.setImgUrl(licenseImg);
                    station.setImgName(ImgName);
                }
            }
            Random random=new Random();
            String result1 = "";
            for (int i = 0; i < 4; i++) {
                result1 += random.nextInt(10);
            }
            int year = cal .get(Calendar.YEAR);
            int month = cal .get(Calendar.MONTH) + 1;
            int yearcount=year-2000;
            String code="S"+yearcount+month+"0001"+result1;
            station.setStationCode(code);
            m=stationService.insertStation(station);
            if(m<=0){
                throw new CustomException("插入油站失败");
            }
            stationResVo.setStationCode(code);
            stationResVo.setStationName(station.getStationName());
            stationResVoList.add(stationResVo);
            Long[] roles={Long.parseLong(19+"")};
            //Station station1=stationService.selectStationList(station).get(0);
            SysUser sysUser=new SysUser();
            sysUser.setDeptId((long) 100);
            sysUser.setUserName(code);
            sysUser.setNickName(station.getStationName());
            sysUser.setUserLevel("2");
            sysUser.setPhonenumber(station.getPhone());
            sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
            sysUser.setStationId(station.getStationId());
            sysUser.setRoleIds(roles);
            sysUser.setEnterpriseId(station.getEnterpriseId());
            sysUserService.insertUser(sysUser);

        }
        return stationResVoList;
    }
}
